//
//  SJRegisterViewController.m
//  WSL
//
//  Created by CJ on 2017/12/8.
//  Copyright © 2017年 sanjuetech. All rights reserved.
//

#import "SJRegisterViewController.h"
#import "SJLoginApi.h"
#import "SJSmsSendApi.h"
#import "SJSmsCheckApi.h"
#import "SJWebViewController.h"

@interface SJRegisterViewController ()

@property (nonatomic, strong) UIScrollView *containView;
@property (nonatomic, strong) UIView *otherLoginView;
@property (nonatomic, strong) UITextField *phoneField;
@property (nonatomic, strong) UIView *phoneBG;
@property (nonatomic, strong) UITextField *verifyField;
@property (nonatomic, strong) UIView *verifyBG;
@property (nonatomic, strong) UIButton *verifyButton;
@property (nonatomic, strong) UIButton *registerButton;

@property (strong, nonatomic) UIButton *agreeButton;
@property (nonatomic, copy) NSString *agreeString; // 1 不允许, 2 允许

@end

@implementation SJRegisterViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [SJStatisticTool beginLogPageView:NSStringFromClass([self class])];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [SJStatisticTool endLogPageView:NSStringFromClass([self class])];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.agreeString = @"2";
    [self setupUI];
}


- (void)setupUI {
    
    [self.view addSubview:self.containView];
    self.containView.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
    
    [self.containView addSubview:self.phoneBG];
    self.phoneBG.sd_layout
    .centerXEqualToView(self.containView)
    .topSpaceToView(self.containView, SJLayoutFrame(125))
    .widthIs(SJLayoutFrame(295))
    .heightIs(SJLayoutFrame(43));
    
    [self.containView addSubview:self.verifyBG];
    self.verifyBG.sd_layout
    .centerXEqualToView(self.containView)
    .topSpaceToView(self.phoneBG, SJLayoutFrame(30))
    .widthIs(SJLayoutFrame(295))
    .heightIs(SJLayoutFrame(43));
    
    [self.containView addSubview:self.registerButton];
    self.registerButton.sd_layout
    .centerXEqualToView(self.containView)
    .topSpaceToView(self.verifyBG, SJLayoutFrame(73))
    .widthIs(SJLayoutFrame(295))
    .heightIs(SJLayoutFrame(43));
    
    UILabel *agreementLabel = [UILabel new];
    agreementLabel.textColor = SJColorHexString(@"#ffffff");
    agreementLabel.font = [UIFont systemFontOfSize:SJLayoutFrame(13)];
    agreementLabel.textAlignment = NSTextAlignmentCenter;
    agreementLabel.text = @"同意思藏用户协议";
    agreementLabel.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(agreementTapAction)];
    [agreementLabel addGestureRecognizer:singleTap];
    
    [self.containView addSubview:agreementLabel];
    agreementLabel.sd_layout
    .topSpaceToView(self.registerButton, SJLayoutFrame(15))
    .centerXEqualToView(self.containView)
    .heightIs(SJLayoutFrame(14));
    [agreementLabel setSingleLineAutoResizeWithMaxWidth:SJScreenW * .5];
    
    
    UILabel *secretLabel = [UILabel new];
    secretLabel.textColor = SJColorHexString(@"#ffffff");
    secretLabel.font = [UIFont systemFontOfSize:SJLayoutFrame(13)];
    secretLabel.textAlignment = NSTextAlignmentCenter;
    secretLabel.text = @"隐私政策";
    secretLabel.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *secretTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(secretTapAction)];
    [secretLabel addGestureRecognizer:secretTap];
    
    [self.containView addSubview:secretLabel];
    secretLabel.sd_layout
    .topSpaceToView(agreementLabel, SJLayoutFrame(15))
    .centerXEqualToView(self.containView)
    .heightIs(SJLayoutFrame(14));
    [secretLabel setSingleLineAutoResizeWithMaxWidth:SJScreenW * .5];
    
    [self.containView addSubview:self.agreeButton];
    self.agreeButton.sd_layout
    .rightSpaceToView(agreementLabel, SJLayoutFrame(10))
    .centerYEqualToView(agreementLabel)
    .widthIs(SJLayoutFrame(18))
    .heightIs(SJLayoutFrame(18));
    
    [self.containView addSubview:self.otherLoginView];
    self.otherLoginView.sd_layout
    .leftSpaceToView(self.containView, SJLayoutFrame(0))
    .rightSpaceToView(self.containView, SJLayoutFrame(0))
    .heightIs(SJLayoutFrame(74))
    .bottomSpaceToView(self.containView, SJLayoutFrame(30));
    
    UIButton *pwLoginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [pwLoginButton setImage:[UIImage imageNamed:@"login_password login"] forState:UIControlStateNormal];
    [pwLoginButton addTarget:self action:@selector(passwordLogin) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.containView addSubview:pwLoginButton];
    
    if (812 == SJScreenH) {
        pwLoginButton.sd_layout
        .rightSpaceToView(self.containView, SJLayoutFrame(20))
        .topSpaceToView(self.containView, SJLayoutFrame(57.5))
        .widthIs(SJLayoutFrame(58))
        .heightIs(SJLayoutFrame(15));
    } else {
        pwLoginButton.sd_layout
        .rightSpaceToView(self.containView, SJLayoutFrame(20))
        .topSpaceToView(self.containView, SJLayoutFrame(17.5))
        .widthIs(SJLayoutFrame(58))
        .heightIs(SJLayoutFrame(15));
    }

    // scrollview自动contentsize
//    [self.containView setupAutoContentSizeWithBottomView:self.otherLoginView bottomMargin:0];
    
}

- (void)agreementTapAction {
    
    SJWebViewController *webVC = [SJWebViewController new];
    webVC.url = [NSURL URLWithString:@"http://i.sanjuetech.com/engine/get_protocol"];
    webVC.title = @"用户协议";
    [self.navigationController pushViewController:webVC animated:YES];
}

- (void)secretTapAction {
    
    SJWebViewController *webVC = [SJWebViewController new];
    webVC.url = [NSURL URLWithString:@"http://i.sanjuetech.com/engine/get_privacy"];
    webVC.title = @"隐私政策";
    [self.navigationController pushViewController:webVC animated:YES];
}


#pragma mark - gerter

- (UIView *)phoneBG {
    
    if (!_phoneBG) {
        
        _phoneBG = [UIView new];
        _phoneBG.sd_cornerRadius = @(SJCornerRadius);
        _phoneBG.backgroundColor = SJColorHexString(@"#ffffff19");
        _phoneBG.layer.borderColor = [UIColor clearColor].CGColor;//边框颜色
        _phoneBG.layer.borderWidth = SJLayoutFrame(1);//边框宽度
        
        UIImageView *leftImage = [UIImageView new];
        leftImage.image = [UIImage imageNamed:@"personal_icon_phone"];
        
        [_phoneBG addSubview:leftImage];
        leftImage.sd_layout
        .centerYEqualToView(_phoneBG)
        .leftSpaceToView(_phoneBG, SJLayoutFrame(10))
        .widthIs(SJLayoutFrame(25))
        .heightIs(SJLayoutFrame(25));
        
        [_phoneBG addSubview:self.phoneField];
        self.phoneField.sd_layout
        .leftSpaceToView(leftImage, SJLayoutFrame(15))
        .topSpaceToView(_phoneBG, SJLayoutFrame(0))
        .rightSpaceToView(_phoneBG, SJLayoutFrame(0))
        .bottomSpaceToView(_phoneBG, SJLayoutFrame(0));
        
    }
    return _phoneBG;
}

- (UIView *)verifyBG {
    
    if (!_verifyBG) {
        
        _verifyBG = [UIView new];
        _verifyBG.sd_cornerRadius = @(SJCornerRadius);
        _verifyBG.backgroundColor = SJColorHexString(@"#ffffff19");
        _verifyBG.layer.borderColor = [UIColor clearColor].CGColor;//边框颜色
        _verifyBG.layer.borderWidth = SJLayoutFrame(1);//边框宽度
        
        UIImageView *leftImage = [UIImageView new];
        leftImage.image = [UIImage imageNamed:@"personal_setpassword_code"];
        
        [_verifyBG addSubview:leftImage];
        leftImage.sd_layout
        .centerYEqualToView(_verifyBG)
        .leftSpaceToView(_verifyBG, SJLayoutFrame(10))
        .widthIs(SJLayoutFrame(25))
        .heightIs(SJLayoutFrame(25));
        
        [_verifyBG addSubview:self.verifyButton];
        self.verifyButton.sd_layout
        .topSpaceToView(_verifyBG, SJLayoutFrame(0))
        .rightSpaceToView(_verifyBG, SJLayoutFrame(0))
        .bottomSpaceToView(_verifyBG, SJLayoutFrame(0))
        .widthIs(SJLayoutFrame(103));
        
        UIView *lineView = [UIView new];
        lineView.backgroundColor = [UIColor whiteColor];
        lineView.alpha = .6;
        
        [_verifyBG addSubview:lineView];
        lineView.sd_layout
        .centerYEqualToView(_verifyBG)
        .rightSpaceToView(self.verifyButton, SJLayoutFrame(0))
        .widthIs(SJLayoutFrame(1))
        .heightIs(SJLayoutFrame(25));
        
        [_verifyBG addSubview:self.verifyField];
        self.verifyField.sd_layout
        .leftSpaceToView(leftImage, SJLayoutFrame(15))
        .topSpaceToView(_verifyBG, SJLayoutFrame(0))
        .rightSpaceToView(lineView, SJLayoutFrame(0))
        .bottomSpaceToView(_verifyBG, SJLayoutFrame(0));
        
    }
    return _verifyBG;
}


- (void)allowCopyAction {
    
    self.agreeButton.selected = !self.agreeButton.selected;
    if (self.agreeButton.selected) {
        self.agreeString = @"2";
    } else {
        self.agreeString = @"1";
    }
}

- (UIButton *)agreeButton {
    
    if (!_agreeButton) {
        
        _agreeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_agreeButton setImage:[UIImage imageNamed:@"btn_allow_collect_nor"] forState:UIControlStateNormal];
        [_agreeButton setImage:[UIImage imageNamed:@"btn_allow_collect_sel"] forState:UIControlStateSelected];
        [_agreeButton addTarget:self action:@selector(allowCopyAction) forControlEvents:UIControlEventTouchUpInside];
        _agreeButton.selected = YES;
    }
    return _agreeButton;
}

#pragma mark 手机号码验证

- (UIButton *)verifyButton{
    
    if (!_verifyButton) {
        
        _verifyButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_verifyButton addTarget:self action:@selector(verifyAction) forControlEvents:UIControlEventTouchUpInside];
        [_verifyButton setTitle:@"发送验证码" forState:UIControlStateNormal];
        _verifyButton.titleLabel.font = [UIFont systemFontOfSize:SJLayoutFrame(13)];
    }
    return _verifyButton;
}

- (BOOL)isValidateMobile:(NSString *)mobile {
    
    NSPredicate* phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"1[345678]([0-9]){9}"];
    
    return [phoneTest evaluateWithObject:mobile];
    
}

- (void)verifyAction {
    
    if (![self isValidateMobile:self.phoneField.text]) {
        
        NSString *msg = @"请输入正确手机号";
        [SVProgressHUD showErrorWithStatus:msg];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    [self openCountdown];
    [self.verifyField becomeFirstResponder];
    
    // 1.拼接参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"phone"] = self.phoneField.text;
    
    SJSmsSendApi *api = [[SJSmsSendApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
    
        } else {
            
            NSString *msg = api.responseObject[@"result"][@"msg"];
            [SVProgressHUD showErrorWithStatus:msg];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
            
        }
        
    } failure:^(YTKBaseRequest *request) {
        
    }];
    
    
}
- (void)openCountdown {
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
    
    NSTimeInterval seconds = 60.f;
    NSDate *endTime = [NSDate dateWithTimeIntervalSinceNow:seconds]; // 最后期限
    
    dispatch_source_set_event_handler(_timer, ^{
        
        int interval = [endTime timeIntervalSinceNow];
        if (interval > 0) { // 更新倒计时
            NSString *timeStr = [NSString stringWithFormat:@"剩余%.0ds", interval];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.verifyButton.enabled = NO;
                [self.verifyButton setTitle:timeStr forState:UIControlStateNormal];
            });
        } else { // 倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.verifyButton.enabled = YES;
                [self.verifyButton setTitle:@"发送验证码" forState:UIControlStateNormal];
            });
        }
    });
    dispatch_resume(_timer);
}

- (UIButton *)registerButton{
    
    if (!_registerButton) {
        
        _registerButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_registerButton addTarget:self action:@selector(registerAction) forControlEvents:UIControlEventTouchUpInside];
        [_registerButton setImage:[UIImage imageNamed:@"login_loginsicang"] forState:UIControlStateNormal];
        
    }
    return _registerButton;
}

- (void)registerAction {
    
    if ([self.agreeString isEqualToString:@"1"]) {
        
        NSString *msg = @"请同意思藏用户协议";
        [SVProgressHUD showInfoWithStatus:msg];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    if (![self.phoneField.text isNotBlank] || ![self.verifyField.text isNotBlank]) {
        
        NSString *msg = @"请输入手机号或验证码";
        [SVProgressHUD showErrorWithStatus:msg];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
  
    // 1.拼接参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"phone"] = self.phoneField.text;
    parameters[@"sms"] = self.verifyField.text;
    parameters[@"type"] = @"1";
    
    SJLoginApi *api = [[SJLoginApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            [SJUserDefaults setObject:api.responseObject[@"content"][@"token"] forKey:SJToken];
            [SJUserDefaults setObject:api.responseObject[@"content"] forKey:SJUserInfo];
            [SJUserDefaults synchronize];
            
            [self dismissViewControllerAnimated:YES completion:nil];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:SJDidLoginNotification object:nil];
            });
        } else {
            
            NSString *msg = api.responseObject[@"result"][@"msg"];
            [SVProgressHUD showErrorWithStatus:msg];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
        }
        
        
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        attributes[@"type"] = @"sms";
        [SJStatisticTool event:@"regitster_sms" attributes:attributes];
        
    } failure:^(YTKBaseRequest *request) {
        
    }];
    
}

- (UITextField *)phoneField{
    
    if (!_phoneField) {
        
        _phoneField = [UITextField new];
        _phoneField.returnKeyType = UIReturnKeyNext;
        _phoneField.keyboardType = UIKeyboardTypePhonePad;
        _phoneField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _phoneField.textColor = SJColorHexString(@"#ffffff");
        _phoneField.font = [UIFont systemFontOfSize:SJLayoutFrame(15)];
        
        // 编辑
        [_phoneField addTarget:self action:@selector(editingDidBegin:) forControlEvents:UIControlEventEditingDidBegin];
        [_phoneField addTarget:self action:@selector(editingDidEnd:) forControlEvents:UIControlEventEditingDidEnd];
        
        NSString *holderText = @"输入手机号";
        NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc]initWithString:holderText];
        [placeholder addAttribute:NSForegroundColorAttributeName
                            value:SJColorHexString(@"#ffffff90")
                            range:NSMakeRange(0, holderText.length)];
        [placeholder addAttribute:NSFontAttributeName
                            value:[UIFont systemFontOfSize:SJLayoutFrame(15)]
                            range:NSMakeRange(0, holderText.length)];
        _phoneField.attributedPlaceholder = placeholder;
        
    }
    return _phoneField;
}

- (void)editingDidBegin:(UITextField *)textField {
    
    if (textField == self.phoneField) {
        _phoneBG.layer.borderColor = [UIColor whiteColor].CGColor;//边框颜色
        
    } else {
        _verifyBG.layer.borderColor = [UIColor whiteColor].CGColor;//边框颜色
    }
}

- (void)editingDidEnd:(UITextField *)textField {
    
    if (textField == self.phoneField) {
        _phoneBG.layer.borderColor = [UIColor clearColor].CGColor;//边框颜色
        
    } else {
        _verifyBG.layer.borderColor = [UIColor clearColor].CGColor;//边框颜色
    }
}

- (UITextField *)verifyField{
    
    if (!_verifyField) {
        
        _verifyField = [UITextField new];
        _verifyField.returnKeyType = UIReturnKeyNext;
        _verifyField.keyboardType = UIKeyboardTypePhonePad;
        _verifyField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _verifyField.textColor = SJColorHexString(@"#ffffff");
        _verifyField.font = [UIFont systemFontOfSize:SJLayoutFrame(15)];
        
        // 编辑
        [_verifyField addTarget:self action:@selector(editingDidBegin:) forControlEvents:UIControlEventEditingDidBegin];
        [_verifyField addTarget:self action:@selector(editingDidEnd:) forControlEvents:UIControlEventEditingDidEnd];
        
        NSString *holderText = @"输入验证码";
        NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc]initWithString:holderText];
        [placeholder addAttribute:NSForegroundColorAttributeName
                            value:SJColorHexString(@"#ffffff90")
                            range:NSMakeRange(0, holderText.length)];
        [placeholder addAttribute:NSFontAttributeName
                            value:[UIFont systemFontOfSize:SJLayoutFrame(15)]
                            range:NSMakeRange(0, holderText.length)];
        _verifyField.attributedPlaceholder = placeholder;
        
    }
    return _verifyField;
}

- (UIScrollView *)containView {
    
    if (!_containView) {
        
        _containView = [UIScrollView new];
        
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapAction)];
        singleTap.cancelsTouchesInView = NO;
        [_containView addGestureRecognizer:singleTap];
        
    }
    return _containView;
}

- (void)singleTapAction {
    
    [self.view endEditing:YES];
}

- (UIView *)otherLoginView {
    
    if (!_otherLoginView) {
        
        _otherLoginView = [UIView new];
        
        UIImageView *lineImage = [UIImageView new];
        lineImage.contentMode = UIViewContentModeScaleAspectFit;
        lineImage.image = [UIImage imageNamed:@"signin_quicklogin"];
        [_otherLoginView addSubview:lineImage];
        lineImage.sd_layout.topSpaceToView(_otherLoginView, 0).centerXEqualToView(_otherLoginView).heightIs(SJLayoutFrame(13)).widthIs(SJScreenW);
        
        UIView *containView = [UIView new];
        [_otherLoginView addSubview:containView];
        containView.sd_layout
        .topSpaceToView(lineImage, SJLayoutFrame(21))
        .centerXEqualToView(_otherLoginView)
        .widthIs(SJLayoutFrame(220))
        .heightIs(SJLayoutFrame(40));
        
        
        NSMutableArray *temp = [NSMutableArray new];
        for (int i = 0; i < 3; i++) {
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            
            NSString *imgName = nil;
            if (i == 0) imgName = @"login_quicklogin_qq";
            if (i == 1) imgName = @"login_quicklogin_wechat";
            if (i == 2) imgName = @"login_quicklogin_blog";
    
            [button setImage:[UIImage imageNamed:imgName] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(otherAction:) forControlEvents:UIControlEventTouchUpInside];
            button.tag = i;
            
            [containView addSubview:button];
            button.sd_layout.heightIs(SJLayoutFrame(40));
            [temp addObject:button];
        }
        
        [containView setupAutoMarginFlowItems:[temp copy] withPerRowItemsCount:temp.count itemWidth:SJLayoutFrame(40) verticalMargin:0 verticalEdgeInset:0 horizontalEdgeInset:0];
        
        [_otherLoginView setupAutoHeightWithBottomView:containView bottomMargin:0];
        
    }
    return _otherLoginView;
}


#pragma mark - 登录 action
- (void)otherAction:(UIButton *)button {
    
    if ([self.agreeString isEqualToString:@"1"]) {
        
        NSString *msg = @"请同意思藏用户协议";
        [SVProgressHUD showInfoWithStatus:msg];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    if (button.tag == 0) {  // qq
        [self qqLogin];
    }
    if (button.tag == 1) {  // 微信
        [self wxLogin];
    }
    
    if (button.tag == 2) {  // 微博
        [self wbLogin];
    }
    
}


- (void)passwordLogin {
    
    SJLoginViewController *loginVC = [SJLoginViewController new];
    [self.navigationController pushViewController:loginVC animated:YES];
}

- (void)wbLogin {
    
    [SVProgressHUD showWithStatus:@"正在登陆..."];
    WeakSelf;
    [ShareSDK getUserInfo:SSDKPlatformTypeSinaWeibo
           onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error)
     {
         if (state == SSDKResponseStateSuccess) {
             
             // 拼接参数
             NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
             
             // 微信原始数据
             parameters[@"uid"] = user.uid;
             parameters[@"nickname"] = user.nickname;
             parameters[@"gender"] = [NSString stringWithFormat:@"%ld", (long)user.gender];
             parameters[@"location"] = user.rawData[@"location"];
             parameters[@"avatar_hd"] = user.rawData[@"avatar_hd"];
             parameters[@"lang"] = user.rawData[@"lang"];
             
             // type: 1 手机号+验证码登录  2 手机号+密码登录  3 第三方QQ登录  4 第三方微信登录 5 第三方微博登录
             parameters[@"type"] = @"5";
             
             [weakSelf thirdLogin:parameters];
             
             NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
             attributes[@"type"] = @"微博";
             [SJStatisticTool event:@"regitster_SinaWeibo" attributes:attributes];
             
         } else {
             [SVProgressHUD dismiss];
         }
     }];
}


- (void)qqLogin {
    
    [SVProgressHUD showWithStatus:@"正在登陆..."];
    WeakSelf;
    [ShareSDK getUserInfo:SSDKPlatformTypeQQ
           onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error)
     {
         if (state == SSDKResponseStateSuccess) {
             
             // 拼接参数
             NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
             
             // 微信原始数据
             parameters[@"openid"] = user.credential.rawData[@"openid"];
             parameters[@"nickname"] = user.rawData[@"nickname"];
             parameters[@"figureurl"] = user.rawData[@"figureurl"];
             parameters[@"figureurl_1"] = user.rawData[@"figureurl_1"];
             parameters[@"figureurl_2"] = user.rawData[@"figureurl_2"];
             parameters[@"figureurl_qq_1"] = user.rawData[@"figureurl_qq_1"];
             parameters[@"figureurl_qq_2"] = user.rawData[@"figureurl_qq_2"];
             parameters[@"gender"] = user.rawData[@"gender"];
             parameters[@"is_yellow_vip"] = user.rawData[@"is_yellow_vip"];
             parameters[@"vip"] = user.rawData[@"vip"];
             parameters[@"yellow_vip_level"] = user.rawData[@"yellow_vip_level"];
             parameters[@"level"] = user.rawData[@"level"];
             parameters[@"is_yellow_year_vip"] = user.rawData[@"is_yellow_year_vip"];
             parameters[@"province"] = user.rawData[@"province"];
             parameters[@"city"] = user.rawData[@"city"];
             
             // type: 1 手机号+验证码登录  2 手机号+密码登录  3 第三方QQ登录  4 第三方微信登录
             parameters[@"type"] = @"3";
             
             [weakSelf thirdLogin:parameters];
             
             NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
             attributes[@"type"] = @"QQ";
             [SJStatisticTool event:@"regitster_QQ" attributes:attributes];
             
         } else {
             [SVProgressHUD dismiss];
         }
     }];
}



- (void)wxLogin {
    
    [SVProgressHUD showWithStatus:@"正在登陆..."];
    WeakSelf;
    [ShareSDK getUserInfo:SSDKPlatformTypeWechat
           onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error)
     {
         if (state == SSDKResponseStateSuccess) {
             
             // 拼接参数
             NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
             
             // 微信原始数据
             parameters[@"openid"] = user.credential.rawData[@"openid"];
             parameters[@"nickname"] = user.rawData[@"nickname"];
             parameters[@"headimgurl"] = user.rawData[@"headimgurl"];
             parameters[@"gender"] = [NSString stringWithFormat:@"%ld", (long)user.gender];
             parameters[@"province"] = user.rawData[@"province"];
             parameters[@"city"] = user.rawData[@"city"];
             parameters[@"sex"] = [NSString stringWithFormat:@"%@", user.rawData[@"sex"]];
             parameters[@"language"] = user.rawData[@"language"];
             parameters[@"unionid"] = user.rawData[@"unionid"];
             
             // type: 1 手机号+验证码登录  2 手机号+密码登录  3 第三方QQ登录  4 第三方微信登录
             parameters[@"type"] = @"4";
             
             [weakSelf thirdLogin:parameters];
             
             
             NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
             attributes[@"type"] = @"Wechat";
             [SJStatisticTool event:@"regitster_Wechat" attributes:attributes];
             
         } else {
             
             [SVProgressHUD dismiss];
         }
         
     }];
}

- (void)thirdLogin:(NSDictionary *)parameters {
    
    SJLoginApi *api = [[SJLoginApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            [SJUserDefaults setObject:api.responseObject[@"content"][@"token"] forKey:SJToken];
            
            [SJUserDefaults setObject:api.responseObject[@"content"] forKey:SJUserInfo];
            [SJUserDefaults synchronize];
            
            [self dismissViewControllerAnimated:YES completion:nil];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:SJDidLoginNotification object:nil];
            });
        }
        
        [SVProgressHUD dismiss];
    } failure:^(YTKBaseRequest *request) {
        [SVProgressHUD dismiss];
    }];
    
}


@end
